package com.example.multithread.practise.linkedlist;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName KthToLast
 * @Description TODO
 * @Author leejiliang
 * @DateTime 2020/6/4 10:12 AM
 * @Version 1.0
 */
@Slf4j
public class KthToLast {
	public static void main(String[] args) {
		ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);
        ListNode listNode4 = new ListNode(4);
        listNode1.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = listNode4;
		log.info(kthToLastDemo(listNode4, 1)+"");
	}
	public static int kthToLastDemo(ListNode head, int k) {
		//1. 翻转链表. 正向找到第 K 个元素
		//2. 算总长度sum-k , 正向第sum-k 个元素
		int i = 0;
		ListNode temp= head;
		while (temp != null) {
			temp = temp.next;
			i++;
		}
		int len = i - k + 1;
		ListNode temp2 = head;
		while (len > 1) {
			temp2 = temp2.next;
			len--;
		}
		return temp2.val;
	}
}
